#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BUFFER_SIZE 32

int g_fd = 0;//全局变量

/* 钩子要求：函数命名一定要有Handler, */
void sigHandler(int num)
{
    printf("hello world2, num:%d\n", num);
    close(g_fd);
    exit(0);//正常退出
}

int main()
{
    signal(SIGINT, sigHandler);// 注册信号

    const char * name = "./test.txt";
    g_fd = open(name, O_RDWR | O_CREAT, 0644);
    if (g_fd == -1)
    {
        perror("open error");
        exit(-1);
    }

    //signal(SIGALRM, SIG_IGN); /* 忽略下面的定时器信号 */
    /* 设置定时器 */
    //alarm(3);

    char buffer[BUFFER_SIZE] = { 0 };
    strcpy(buffer, "hello world\n");


    int count = 10;
    int writeBytes = 0;
    while (count--)
    {
        writeBytes = write(g_fd, buffer, strlen(buffer) + 1);
        printf("write Bytes:%d\n", writeBytes);
        if (writeBytes < 0)
        {
            perror("write error");
            exit(-1);
        }
        sleep(1);
        
    }
    /* 关闭描述符 */
    close(g_fd);
    return 0;
}